<?php
namespace app\api\controller;
use app\model\ArticleModel;
use app\model\ShuomingModel;
use app\model\SlideModel;
use app\model\WanjiaArticleModel;
use app\model\WanjiaBrowseModel;
use app\model\WanjiaCateModel;
use app\model\WanjiaCommentModel;
use app\model\WanjiaFavoriteModel;
use app\model\WanjiaLikeModel;
use app\model\WanjiaSpecialArticleModel;
use app\model\WanjiaSpecialCommentModel;
use app\model\WanjiaVideoCommentModel;
use app\model\WanjiaVideoModel;
use support\Request;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Tms\V20201229\TmsClient;
use TencentCloud\Tms\V20201229\Models\TextModerationRequest;
use TencentCloud\Ims\V20201229\ImsClient;
use TencentCloud\Ims\V20201229\Models\ImageModerationRequest;

use think\facade\Db;
use tool\User;

class ArcController extends Base
{
    //搜索列表
    public function getSearchList(Request $request){
        $pageNo = $request->post('pageNo',1);
        $pageSize = $request->post('pageSize',10);
        $key=$request->post('key','');
        $list=WanjiaArticleModel::alias('a')
            ->join('wanjia_comment b','a.id=b.arc_id','left')
            ->where('a.isopen',1)->where('a.title|a.desc', 'like', '%'.$key.'%')
            ->field('a.id,a.title,a.desc,a.pic,a.click,a.zan,a.update_time,count(b.id) as comment_num')
            ->group('a.id') // 关键：按文章 ID 分组统计评论数
            ->order('a.is_tui asc, a.update_time desc, a.id desc') // 建议调整排序顺序（可选）
            ->page($pageNo,$pageSize)->select()->toArray();
        s($list);
    }
    //获取评论
    public function getCommentList(Request $request){
        $user=User::findMe();
        $pageNo = $request->post('pageNo',1);
        $pageSize = $request->post('pageSize',10);

        $subQuery = Db::name('wanjia_comment')->where('uid',$user['id'])
            ->field('arc_id, MAX(id) as latest_comment_id')
            ->group('arc_id')->buildSql();
        $list = Db::table($subQuery . ' sub') // 子查询包裹为派生表
            ->join('wanjia_comment b', 'sub.latest_comment_id = b.id') // 关联评论表
            ->join('wanjia_article a', 'sub.arc_id = a.id') // 关联文章表
            ->field('a.id, a.title, a.desc, a.pic, a.click, a.zan, a.update_time, b.comment,b.create_time as time')
            ->where('a.isopen', 1)
            ->order('sub.latest_comment_id DESC')
            ->page($pageNo, $pageSize)
            ->select()->each(function($item){
                $item['time'] = date('Y-m-d H:i:s',$item['time']);
                $item['update_time'] = date('Y-m-d H:i:s',$item['update_time']);
                return $item;
            })
            ->toArray();
        s($list);
    }
    //获取收藏
    public function getFavoriteList(Request $request){
        $user=User::findMe();
        $pageNo = $request->post('pageNo',1);
        $pageSize = $request->post('pageSize',10);
        $index=$request->post('index',0);
        $list=[];
        if($index==1){
            $list = WanjiaLikeModel::alias('bb')
                ->join('wanjia_article a', 'bb.arc_id=a.id', 'left')
                ->join('wanjia_comment b', 'a.id=b.arc_id', 'left')
                ->field(['a.id','a.title', 'a.desc', 'a.pic', 'a.click','a.zan','a.update_time','COUNT(b.id) as comment_num','MAX(bb.update_time) as latest_update_time'])
                ->where('a.isopen', 1)->where('bb.uid', $user['id'])->where('bb.pType', 1)
                ->group('a.id')->order('latest_update_time DESC') // 按聚合后的时间排序
                ->page($pageNo, $pageSize)->select()->toArray();
        }
        if($index==2){
            $list = WanjiaFavoriteModel::alias('bb')
                ->join('wanjia_article a', 'bb.arc_id=a.id', 'left')
                ->join('wanjia_comment b', 'a.id=b.arc_id', 'left')
                ->field(['a.id','a.title', 'a.desc', 'a.pic', 'a.click','a.zan','a.update_time','COUNT(b.id) as comment_num','MAX(bb.update_time) as latest_update_time'])
                ->where('a.isopen', 1)->where('bb.uid', $user['id'])->where('bb.pType', 1)
                ->group('a.id')->order('latest_update_time DESC') // 按聚合后的时间排序
                ->page($pageNo, $pageSize)->select()->toArray();
        }
        if($index==3){
            $list = WanjiaBrowseModel::alias('bb')
                ->join('wanjia_article a', 'bb.arc_id=a.id', 'left')
                ->join('wanjia_comment b', 'a.id=b.arc_id', 'left')
                ->field(['a.id','a.title', 'a.desc', 'a.pic', 'a.click','a.zan','a.update_time','COUNT(b.id) as comment_num','MAX(bb.update_time) as latest_update_time'])
                ->where('a.isopen', 1)->where('bb.uid', $user['id'])->where('bb.pType', 1)
                ->group('a.id')->order('latest_update_time DESC') // 按聚合后的时间排序
                ->page($pageNo, $pageSize)->select()->toArray();
        }
        s($list);
    }
    //获取更多信息
    public function getGengduoList(Request $request){
        $list=ShuomingModel::where('isopen',1)->order('create_time asc,id desc')->field('id,title')->select()->toArray();
        s($list);
    }
    //更多的详情
    public function getGengduoListOne(Request $request){
        $id=$request->post('id',0);
        $list=ShuomingModel::where('id',$id)->field('id,title,text')->find();
        s($list);
    }
    //点赞
    public function updateArcZan(Request $request){
        $id=$request->post('id',0);
        $pType=$request->post('pType',0);
        $user=User::findMe();
        if(!$user['id']){
            e('请先登录');
        }
        if(!$id){
            e('点赞失败');
        }
        $one=WanjiaLikeModel::where('arc_id',$id)->where('uid',$user['id'])->where('pType',$pType)->find();
        if($one){
            if($pType==1){
                WanjiaArticleModel::where('id',$id)->update(['zan'=>Db::raw('zan-1')]);
            }
            if($pType==2){
                WanjiaVideoModel::where('id',$id)->update(['zan'=>Db::raw('zan-1')]);
            }
            if($pType==3){
                WanjiaSpecialModel::where('id',$id)->update(['zan'=>Db::raw('zan-1')]);
            }
            $w=WanjiaLikeModel::where('id',$one['id'])->update(['delete_time'=>time()]);
        }else{
            if($pType==1){
                WanjiaArticleModel::where('id',$id)->update(['zan'=>Db::raw('zan+1')]);
            }
            if($pType==2){
                WanjiaVideoModel::where('id',$id)->update(['zan'=>Db::raw('zan+1')]);
            }
            if($pType==3){
                WanjiaSpecialModel::where('id',$id)->update(['zan'=>Db::raw('zan+1')]);
            }
            WanjiaLikeModel::create([
                'uid'=>$user['id'],
                'arc_id'=>$id,
                'pType'=>$pType
            ]);
        }
        s();
    }

    //收藏
    public function updateArcShou(Request $request){
        $id=$request->post('id',0);
        $pType=$request->post('pType',0);
        $user=User::findMe();
        if(!$user['id']){
            e('请先登录');
        }
        if(!$id){
            e('点赞失败');
        }
        $one=WanjiaFavoriteModel::where('arc_id',$id)->where('uid',$user['id'])->where('pType',$pType)->find();
        if($one){
            WanjiaFavoriteModel::where('id',$one['id'])->update(['delete_time'=>time()]);
        }else{
            WanjiaFavoriteModel::create([
                'uid'=>$user['id'],
                'arc_id'=>$id,
                'pType'=>$pType
            ]);
        }
        s();
    }
    //获取分享信息
    public function getShareList(Request $request){
        $id=$request->post('id',0);
        $pType=$request->post('pType',0);
        $one='';
        $title='';
        $summary='';
        $imageUrl='';
        if($pType==1){
            $one=WanjiaArticleModel::where('id',$id)->find();
        }
        if($pType==2){
            $one=WanjiaVideoModel::where('id',$id)->find();
        }
        if($pType==3){
            $one=WanjiaSpecialArticleModel::where('id',$id)->find();
        }
        if($one and $one['pic']){
            $imageUrl=$one['pic'];
        }
        if($one and $one['title']){
            $title=$one['title'];
        }
        if($one and $one['desc']){
            $summary=$one['desc'];
        }
        $href=route('share',['id'=>$id,'type'=>$pType]);
        s([
            "href"=>$href,
            "title"=>$title,
            "summary"=>$summary,
            "imageUrl"=>$imageUrl
        ]);
    }


    //留言
    public function updateArcComment(Request $request){
        $id=$request->post('id',0);
        $content=$request->post('content','');
        $pType=$request->post('pType',0);
        $user=User::findMe();
        if(!$user['id']){
            e('请先登录');
        }
        if(!$id || !$content || !$pType){
            e('留言失败');
        }
        //判断是否有非法数据
        // 初始化客户端
        $cred = new Credential("AKIDWt30iDTeePvDSWO3VigQu98sNfjT0MWS","kHl4B6oJaeUCXheMwIQL2VmqjNo20jDS");
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("tms.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new TmsClient($cred, "ap-guangzhou", $clientProfile);

// 构建请求
        $req = new TextModerationRequest();
        $params = [
            "Content" => base64_encode($content), // 必须Base64编码
            "BizType" => "wanjialiuyan" // 业务类型，需在控制台配置
        ];
        $req->fromJsonString(json_encode($params));

// 发送请求
        try {
            $resp = $client->TextModeration($req);
            $arr=json_decode($resp->toJsonString(),true);
//            print_r($resp->toJsonString());
            if($arr["Suggestion"]== "Block"){
                e("请勿发布违法违规内容,请调整后提交！");
            }

            if($pType==1){
                WanjiaCommentModel::create([
                    'uid'=>$user['id'],
                    'arc_id'=>$id,
                    'comment'=>$content
                ]);
            }
            if($pType==2){
                WanjiaVideoCommentModel::create([
                    'uid'=>$user['id'],
                    'arc_id'=>$id,
                    'comment'=>$content
                ]);
            }
            if($pType==3){
                WanjiaSpecialCommentModel::create([
                    'uid'=>$user['id'],
                    'arc_id'=>$id,
                    'comment'=>$content
                ]);
            }
            s();


        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
            e("留言失败，文本审核失败，请稍后重试！");
        }



    }


    public function getArcNav(Request $request)
    {
        $data=WanjiaCateModel::where('isopen',1)->field('id as value,catename as name')->order('sort asc,id asc')->select()->toArray();
        array_unshift($data, [
            'value'=>0,
            'name'=>'推荐'
        ]);
        s($data);
    }
    //获取首页头部
    public function getArcListTop(Request $request){
        $topList=WanjiaArticleModel::alias('a')
            ->where('a.isopen',1)
            ->field('a.id,a.title,a.desc,a.pic,a.click,a.zan,a.update_time')
            ->order('a.is_tui asc,a.zan desc, a.update_time desc, a.id desc') // 建议调整排序顺序（可选）
            ->limit(5)->select()->toArray();

        $list=SlideModel::field('id,title,img as image')->order('sort asc,id asc')->select()->toArray();
        s([
            'topList'=>$topList,
            'list'=>$list
        ]);
    }

    public function getArcList(Request $request)
    {
        $pageNo = $request->post('pageNo',1);
        $pageSize = $request->post('pageSize',10);
        $type = $request->post('type',1);
        $dingweiCode = $request->post('code',1); //定位
        if($type==100){
            $list=WanjiaArticleModel::alias('a')
                ->join('wanjia_comment b','a.id=b.arc_id','left')
                ->where('a.isopen',1)
                ->where('a.shi',$dingweiCode)
                ->field('a.id,a.title,a.desc,a.pic,a.click,a.zan,a.update_time,count(b.id) as comment_num')
                ->group('a.id') // 关键：按文章 ID 分组统计评论数
                ->order('a.is_tui asc, a.update_time desc, a.id desc') // 建议调整排序顺序（可选）
                ->page($pageNo,$pageSize)->select()->toArray();
        }elseif ($type==0){
            $list=WanjiaArticleModel::alias('a')
                ->join('wanjia_comment b','a.id=b.arc_id','left')
                ->where('a.isopen',1)
                ->field('a.id,a.title,a.desc,a.pic,a.click,a.zan,a.update_time,count(b.id) as comment_num')
                ->group('a.id') // 关键：按文章 ID 分组统计评论数
                ->order('a.is_tui asc, a.update_time desc, a.id desc') // 建议调整排序顺序（可选）
                ->page($pageNo,$pageSize)->select()->toArray();
        }else{
            $list=WanjiaArticleModel::alias('a')
                ->join('wanjia_comment b','a.id=b.arc_id','left')
                ->where('a.isopen',1)->where('a.cateid',$type)
                ->field('a.id,a.title,a.desc,a.pic,a.click,a.zan,a.update_time,count(b.id) as comment_num')
                ->group('a.id') // 关键：按文章 ID 分组统计评论数
                ->order('a.is_tui asc, a.update_time desc, a.id desc') // 建议调整排序顺序（可选）
                ->page($pageNo,$pageSize)->select()->toArray();
        }
        s($list);
    }

    public function getArcOne(Request $request)
    {
        $id = $request->post('id',0);
        WanjiaArticleModel::where('id', $id)->update(['click'=>Db::raw('click+1'),'click_wai'=>Db::raw('click_wai+1')]);
        //记录浏览
        $user=User::findMe();
        if($user['id']){
            WanjiaBrowseModel::create([
                'uid'=>$user['id'],
                'arc_id'=>$id,
                'pType'=>1,
            ]);
        }
        $list=WanjiaArticleModel::alias('a')
            ->join('wanjia_like b','a.id=b.arc_id and b.delete_time is null and b.pType=1','left')
            ->join('wanjia_favorite c','a.id=c.arc_id and c.delete_time is null  and b.pType=1','left')
            ->where('a.id', $id)
            ->field('a.*,c.id as favorite_id,b.id as like_id')
            ->find();
        s($list);
    }
    public function getcommentsOne(Request $request)
    {
        $id = $request->post('id',0);
        $list=WanjiaCommentModel::alias('a')
            ->join('user b','a.uid=b.id','left')
            ->field('a.*,b.nickName,b.img')
            ->where('a.arc_id', $id)->order('a.id desc')->select();
        s($list);
    }
}
